package com.atguigu.controller;

import com.atguigu.model.system.SysUser;
import com.atguigu.result.Result;
import com.atguigu.service.SysUserService;
import com.atguigu.utils.JwtHelper;
import com.atguigu.vo.wechat.BindPhoneVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/admin/wechat")
@CrossOrigin
public class WechatController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private WxMpService wxMpService;
    @Value("${wechat.userInfoUrl}")
    private String userInfoUrl;
    @GetMapping("authorize")
    public String authorize(String returnUrl){
        try {
            //笔记
            //由于授权回调成功后，要返回原地址路径，原地址路径带“#”号，当前returnUrl获取带“#”的url获取不全，因此前端把“#”号替换为“sdps”了，这里要还原一下
            String authorizationUrl = wxMpService.getOAuth2Service().buildAuthorizationUrl(userInfoUrl, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl.replace("sdpsb", "#"), "utf-8"));
            System.out.println(authorizationUrl);
            return "redirect:"+authorizationUrl;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
    @GetMapping("userInfo")
    public String getUserInfo(String code, String state){
        System.out.println("code"+code);
        System.out.println("state"+state);
        try {
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            String openId = accessToken.getOpenId();
            LambdaQueryWrapper<SysUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysUser::getOpenId,openId);
            SysUser sysUser = sysUserService.getOne(lambdaQueryWrapper);
            String token="";
            if (null!=sysUser){
                //说明用户之前已经绑定过openId，直接生成token
                 token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
            }
            if (state.indexOf("?")==-1){
                //说明源地址不带参数
                return "redirect:"+state+"?token="+token+"&openId="+openId;
            }else{
                //说明源地址带参数
                return "redirect:"+state+"&token="+token+"&openId="+openId;
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            return null;
        }
    }
    @PostMapping("bindPhone")
    @ResponseBody
    public Result bindPhone(@RequestBody BindPhoneVo bindPhoneVo){
        String phone = bindPhoneVo.getPhone();
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getPhone,phone);
        SysUser sysUser = sysUserService.getOne(lambdaQueryWrapper);
        if (null!=sysUser){
            String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
            sysUser.setOpenId(bindPhoneVo.getOpenId());
            sysUserService.updateById(sysUser);
            return Result.ok(token);
        }else{
            return Result.fail().message("手机号码不存在！！！！");
        }

    }
}
